package Threads;

import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.sdwfqin.cbt.CbtManager;
import com.sdwfqin.cbt.Content;

import utils.JX_Utils;
import xm.chengdu.com.beijing_211.Thread.YanZheng;

/**
 *
 */
public class BluetoothCommunicateThread2 extends Thread {
    private Handler handler; // 与Service通信的Handler
    private BluetoothSocket socket;
    private InputStream inputStream; // 对象输入流
    private OutputStream outStream; // 对象输出流
    public static YanZheng resolveDataUtil = new YanZheng();
    /**
     * false:停止运行  线程是否运行
     */
//    public static boolean isRun = false; // 运行标志位
    int nRet = 0;

    private byte[] sendBuffer = null;
    Context context;




    public BluetoothCommunicateThread2(Handler handler,
                                       BluetoothSocket bluetoothSocket, Context context) {
        // Log.e("88",
        // "88bluetooth socket=" + socket + ",isConnected="
        // + socket.isConnected());
        this.handler = handler;
        this.socket = bluetoothSocket;
        this.context = context;
        try {
            this.outStream = socket.getOutputStream();
            this.inputStream = socket.getInputStream();
            this.recvbytes = new byte[50];

        } catch (Exception e) {
            try {
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            // 发送连接失败消息
            // SendLoop.getExceptionMessage("Error连接失败,请重连");
            Message msg = new Message();
            msg.what = 2;
            handler.sendMessage(msg);

        }

    }

    int length = 0;
    String copyString;
    private byte[] recvbytes  ;
    byte[] byteSend = null;
      @Override
     public void run() {
        super.run();
//          Log.e("test",""+isRun);
       while (CbtManager.isRun) {
               try {
                   if (inputStream!=null&&socket != null && socket.isConnected()) {
                       length = inputStream.read(recvbytes);
                   }

//                   Log.e("test",""+length);
                   if (length > 0) {
//                           Log.e("test", Arrays.toString(recvbytes));
//                   Log.e("test",
//                           "接收底层数据"
//                                   + HexUtil.BytesToString(recvbytes, 0,
//                                   length));
                       nRet = resolveDataUtil.Analy55AA(recvbytes, length);
                       Log.e("test", "nRet=" + nRet);
                       if (nRet == 0) {

                           byteSend = resolveDataUtil.GetFrameData55AA();
                           copyString = byte2HexStr(this.byteSend).trim();
                           Log.e("test", "接收底层返回结果" + copyString);
                           Message msg = new Message();
                           msg.what = 3;
                           msg.obj=copyString;
                           handler.sendMessage(msg);
                       }else  if (nRet == 3) {
                           Message msg = new Message();
                           msg.what = 4;

                           handler.sendMessage(msg);
                       }

                   } else {
                       Thread.sleep(10);
                   }
               } catch (Exception e) {

                   Log.e("test", "错误结果" +   e.toString());
                   if (inputStream!= null) {
                       try {

                           inputStream.close();
                           inputStream=null;
                       } catch (IOException e1) {
                           e1.printStackTrace();
                       }
                   }
                   if (outStream!= null) {
                       try {
                           outStream.close();
                           outStream=null;
                       } catch (IOException e1) {
                           e1.printStackTrace();
                       }
                   }
                   if (socket != null && socket.isConnected()) {
                       try {
                           socket.close();
                           Content.isConn = false;
                           Log.i("BluetoothUtil", "stopConn");
                       } catch (IOException es) {
                           es.printStackTrace();
                       }
                   } else {
                       Content.isConn = false;
                   }
               }


           }

      }


public  void  close(){
    if (inputStream!= null) {
        try {
            inputStream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    if (outStream!= null) {
        try {
            outStream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    if (socket!= null) {
        try {
            socket.close();
            socket=null;
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

}



    public static String byte2HexStr(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length);
        String sTemp = "";

        for (int i = 0; i < b.length; ++i) {
            try {
                sTemp = Integer.toHexString(255 & b[i]);
            } catch (Exception var5) {
                System.err.println("bytesToHexString() bArray[" + i + "]=" + b[i]);
                var5.printStackTrace();
            }

            if (sTemp.length() < 2) {
                sb.append(0);
            }

            sb.append(sTemp.toUpperCase());
        }

        return sb.toString();
    }

    public void sendMessage(byte[] b) {
        if (socket != null) {
            try {
                if (b.length > 0) {
                    outStream.write(b);
                }
                outStream.flush();
                Log.e("777", "7777");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage(String msg) {
        Log.e("发送数据22", "xx"+msg);
        if (socket != null) {
            try {
                int datalen = msg.getBytes().length;
                int bytelen = 0;
                if ((datalen % 2) == 0)
                    bytelen = (int) (datalen / 2);
                else
                    bytelen = (int) (datalen / 2) + 1;

                sendBuffer = new byte[bytelen];
                int i = 0, j = 0;
                while (i < datalen) {
                    while (i >= 0 && (!CharInRange(msg.charAt(i))))
                        i++;

                    if (((i + 1) >= datalen)
                            || (!CharInRange(msg.charAt(i + 1)))) {
                        sendBuffer[j] = StrToByte(String.valueOf(msg.charAt(i)));
                        j++;
                    } else {
                        sendBuffer[j] = StrToByte(msg.substring(i, i + 2));
                        j++;
                    }

                    i += 2;
                }
                for (int m = 0; i < sendBuffer.length; m++) {
                    System.out.print(sendBuffer[m]);
                }
                outStream = new DataOutputStream(socket.getOutputStream());
                if (sendBuffer.length > 0) {
                    outStream.write(sendBuffer);
                }
                outStream.flush();
            } catch (Exception e) {
                Log.e("发送数据22", "xx"+e);
                Log.e("发送数据22", "--not connected 4--");
            }
        } else {
            Log.e("发送数据22", "--not connected 5--");
        }
    }

    private boolean CharInRange(char c) {
        boolean result = false;
        if (c >= '0' && c <= '9')
            result = true;
        if (c >= 'a' && c <= 'f')
            result = true;
        if (c >= 'A' && c <= 'F')
            result = true;
        return result;
    }

    private byte StrToByte(String s) {
        return Integer.valueOf(String.valueOf(Integer.parseInt(s, 16)))
                .byteValue();
    }


    public static int getzhi(String shi) {
        String substring = shi.substring(6, 10);
        int hexStringToInt = JX_Utils.hexStringToInt(substring);
        String substring2 = shi.substring(12, 12 + hexStringToInt * 2);
        int zong = JX_Utils.hexStringToInt(substring2);
        return zong;

    }


}
